package com.matt.controller.group;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dotflat.util.excelUtil.StringUtils;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.photoalbum.PhotoAlbumStatic;
import com.matt.foundation.model.ErrorCode;
import com.matt.service.Photo.PhotoAlbumStaticPageService;
import com.matt.service.remoteCall.DTO.SsoAreaDTO;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/web/group/static_photo_album")
@Slf4j
@Api(tags = "Web集团 - 静态相册管理")
public class WebGroupPhotoAlbumStaticPageController {

    @Autowired
    private PhotoAlbumStaticPageService photoAlbumService;

    @Autowired
    private SsoCallService ssoCallService;

    @GetMapping("/list")
    @ApiOperation(value = "列表集团下所有相册")
    public StatusResponse albumList(@RequestHeader(TICKET) String ticket,
                                            String keyword,
                                            PagerQuery pagerQuery ){
        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);
        List<String> ids = areaDTOList.stream().map(o->o.getId()).collect(Collectors.toList());
        Page<PhotoAlbumStatic> result = photoAlbumService.getAllGroupAlbums(keyword, ids, pagerQuery);

        Map<String, SsoAreaDTO> areaCache = areaDTOList.stream().collect(Collectors.toMap(SsoAreaDTO::getId, o->o));
        if (areaCache.size() > 0 ){
            result.getContent().stream().forEach(o->{
                SsoAreaDTO dto = areaCache.get(o.getAreaId());
                if (dto != null) {
                    o.setAreaName(dto.getAreaName());
                }
            });
        }

        return StatusResponse.success(result);
    }

    @GetMapping("/detail")
    @ApiOperation(value = "相册详情")
    public StatusResponse albumDetail(@RequestHeader(TICKET) String ticket, String albumId ){
        PhotoAlbumStatic album = photoAlbumService.photoAlbumById(albumId);
        return StatusResponse.success(album);
    }

    @PostMapping("/confirmReq")
    @ApiOperation(value = "确认已经打印")
    public StatusResponse confirmReq(@RequestHeader(TICKET) String ticket, Boolean comfirmed, String albumId ){
        PhotoAlbumStatic album = photoAlbumService.confirmReq(comfirmed, albumId);
        return StatusResponse.success(album);
    }


    @GetMapping("/download")
    @ApiOperation(value = "下载相册内容")
    @ResponseBody
    public ResponseEntity downloadAlbum(HttpServletRequest req, HttpServletResponse resp, String albumId ){
        try {
            // 创建一个内存中的ZIP文件
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            PhotoAlbumStatic album = photoAlbumService.photoAlbumById(albumId);
            if (album == null || StringUtils.isBlank(album.getAlbumMeta())){
                throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "指定对象不存在");
            }

            JSONObject albumMeta = JSON.parseObject(album.getAlbumMeta());

            JSONArray metas = albumMeta.getJSONArray("metas");

            Set<String> urls = new HashSet<>();
            for (int i = 0; i < metas.size(); i++){
                JSONObject meta = metas.getJSONObject(i);
                List imgs = meta.getJSONArray("imgs");
                urls.addAll((Collection<? extends String>) imgs.stream().map(o->o.toString()).collect(Collectors.toList()));
            }

            try (ZipOutputStream zos = new ZipOutputStream(baos)) {
                for (String url : urls) {
                    // 使用HttpClient下载文件
                    byte[] fileData = downloadFile(url);

                    // 将文件添加到ZIP中
                    ZipEntry zipEntry = new ZipEntry(getFileNameFromUrl(url));
                    zos.putNextEntry(zipEntry);
                    zos.write(fileData);
                    zos.closeEntry();
                }
            }

            // 构建HTTP响应，将ZIP文件返回给客户端
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "album_imgs.zip");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Error downloading files: " + e.getMessage());
        }
    }

    private byte[] downloadFile(String url) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                }
            }
        }
        return null;
    }

    private String getFileNameFromUrl(String url) {
        // 根据URL获取文件名的逻辑，你可以根据实际情况进行实现
        // 这里简单地截取URL的最后一部分作为文件名
        int lastSlashIndex = url.lastIndexOf("/");
        if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
            return url.substring(lastSlashIndex + 1);
        }
        return "file";
    }
}
